package com.yzdmw.toutiao.searchPage;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.yzdmw.toutiao.R;

public class SearchFragment extends Fragment {

    private SearchViewModel mViewModel;
    private SearchView mSearchView;
    private FlexboxLayout flexboxLayout;

    public static SearchFragment newInstance() {
        return new SearchFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.search_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(SearchViewModel.class);
        mSearchView = this.getView().findViewById(R.id.search_view);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchView.clearFocus();
                return true;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                return true;
            }
        });

        flexboxLayout = getView().findViewById(R.id.flexbox_layout);
        mViewModel.getTags().observe(getViewLifecycleOwner(), new Observer<String[]>() {
            @Override
            public void onChanged(@Nullable final String[] array) {
                // Update the UI, in this case, a TextView.
                for (int i = 0;i < array.length;i++) {
                    LinearLayout layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.label_item,null);
                    TextView textview = layout.findViewById(R.id.text_item);
                    textview.setText(array[i]);
                    flexboxLayout.addView(layout);
                    layout.setOnClickListener(view -> {
                        if(view.isSelected()) {
                            view.setSelected(false);
                        }
                        else{
                            view.setSelected(true);
                        }
                    });
                }
            }
        });

    }

}